package com.xpwu.secondary.rabbitmq.consumer;

import com.rabbitmq.client.Channel;
import com.xpwu.secondary.bo.CommonOrderBO;
import com.xpwu.secondary.entity.Order;
import com.xpwu.secondary.mapper.OrderMapper;
import com.xpwu.secondary.utils.Assertion;
import com.xpwu.secondary.utils.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: caoxue
 * @date: 2019/10/14 21:34
 * @description:
 * @version: 1.0
 */
@Configuration
@Slf4j
public class OrderConsumer {

    @Autowired
    private OrderMapper orderMapper;

    @RabbitListener(queues = "SECONDARY_ORDER_QUEUE", containerFactory = "commomFactory")
    public void onMessage(Message message, Channel channel) throws IOException {
        try {
            String body = new String(message.getBody(), Charset.forName("UTF-8"));
            log.info("orderConsumer is ok!传入参数：" + body);
            CommonOrderBO bo = (CommonOrderBO) JacksonUtils.jsonToBean(body, CommonOrderBO.class);
            // 超时 查询订单状态 若已完成，则不处理，反之自动取消
            Order order = orderMapper.selectByPrimaryKey(bo.getOrderId());
            Assertion.notNull(order, "订单信息不存在");
            // 订单还未取消或未结算 自动取消
            boolean trade = order.getPayStatus() == 1 || order.getPayStatus() == 4;
            if (order.getTradeStatus() == 1 && trade) {
                Order update = new Order();
                update.setOrderId(order.getOrderId());
                update.setTradeStatus(2);
                update.setUpdateTime(new Date());
                orderMapper.updateByPrimaryKeySelective(update);
            }
        } catch (Exception e) {
            log.error("orderConsumer is Exception! 错误信息:", e);
        } finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
